package com.yxj.dries.lib.network.response;

import android.os.Handler;
import android.os.Looper;

import com.alibaba.fastjson.JSONObject;
import com.yxj.dries.lib.network.exception.OkHttpException;
import com.yxj.dries.lib.network.listener.DisposeDataHandle;
import com.yxj.dries.lib.network.listener.DisposeDataListener;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 专门处理JSON的回调
 *
 * @author ZSY
 */
public class CommonJsonCallback implements Callback {

    /**
     * the logic layer exception, may alter in different app
     */
    protected final String EMPTY_MSG = "";
    protected final String RESULT_CODE = "encode"; // 有返回则对于http请求来说是成功的，但还有可能是业务逻辑上的错误
    protected final int RESULT_CODE_VALUE = 0;
    protected final String ERROR_MSG = "msg";

    /**
     * the java layer exception, do not same to the logic error
     */
    protected final int NETWORK_ERROR = -1; // the network relative error
    protected final int JSON_ERROR = -2; // the JSON relative error
    protected final int OTHER_ERROR = -3; // the unknow error

    /**
     * 将其它线程的数据转发到UI线程
     */
    private Handler mDeliveryHandler;
    private DisposeDataListener mListener;
    private Class<?> mClass;

    public CommonJsonCallback(DisposeDataHandle handle) {
        mListener = handle.mListener;
        mClass = handle.mClass;
        mDeliveryHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void onFailure(@NotNull final Call call, @NotNull final IOException e) {
        /**
         * 此时还在非UI线程，因此要转发
         */
        mDeliveryHandler.post(new Runnable() {
            @Override
            public void run() {
                mListener.onFailure(new OkHttpException(NETWORK_ERROR, e.getMessage()));
            }
        });
    }

    @Override
    public void onResponse(@NotNull final Call call, @NotNull final Response response) throws IOException {
        final String result = response.body().string();
        mDeliveryHandler.post(new Runnable() {
            @Override
            public void run() {
                handleResponse(result);
            }
        });
    }

    private void handleResponse(Object response) {
        if (response == null || response.toString().trim().equals("")) {
            mListener.onFailure(new OkHttpException(NETWORK_ERROR, EMPTY_MSG));
            return;
        }

        /*
          协议确定后看这里如何修改
         */
        JSONObject result = JSONObject.parseObject(response.toString());
        if (mClass == null) {
            mListener.onSuccess(result);
        } else {
            Object object = JSONObject.parseObject(response.toString(), mClass);
            if (object != null) {
                mListener.onSuccess(object);
            } else {
                mListener.onFailure(new OkHttpException(JSON_ERROR, EMPTY_MSG));
            }
        }
    }
}
